// pages/goodsXiangqing/putongGoods/putongGoods.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    leiIndex: '',
    headIndex: 0,
    goodsid: '',
    goodsinfo: '',
    daixiaojs: '',
    lingshoujs: '',
    jiesuanjs: '',
    timer: '', //定时器名称
    countDownList: [], //显示时间列表
    actEndTimeList: [], //时间列表
    ifstart: 1, //1正在进行2还未开始
    quyulist: [],
    fixindex: 3
  },
  timeFormat: function timeFormat(param) {
    //小于10的格式化函数
    return param < 10 ? "0" + param : param;
  },
  //获取时间
  countDown: function countDown() {
    console.log('倒计时')
    var that = this;
    //倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    var newTime = new Date().getTime();
    var endTimeList = that.data.actEndTimeList;
    var countDownList = [];
    // 对结束时间进行处理渲染到页面
    endTimeList.forEach(function(o) {
      var endTime = new Date(o).getTime();
      var obj = null;
      var time = 0;
      // 如果活动未结束，对时间进行处理
      if (endTime - newTime > 0) {
        var _time = (endTime - newTime) / 1000;
        // 获取天、时、分、秒
        var day = parseInt(_time / (60 * 60 * 24));
        var hou = parseInt(_time % (60 * 60 * 24) / 3600);
        var min = parseInt(_time % (60 * 60 * 24) % 3600 / 60);
        var sec = parseInt(_time % (60 * 60 * 24) % 3600 % 60);
        obj = {
          day: that.timeFormat(day),
          hou: that.timeFormat(hou),
          min: that.timeFormat(min),
          sec: that.timeFormat(sec)
        };
        // obj = obj.day + "天" + obj.hou + ":" + obj.min + ":" + obj.sec;
      } else {
        that.clear()
        //活动已结束，全部设置为'00'
        obj = {
          day: "00",
          hou: "00",
          min: "00",
          sec: "00"
        };
        /// -------
        if (that.data.ifstart == 2) {
          that.getgoodsinfo()
        } else {
          wx.showToast({
            title: '活动已结束',
            icon: 'none'
          })
          that.setData({
            ifstart: 3
          })
          return
        }
        // obj = obj.day + "天" + obj.hou + ":" + obj.min + ":" + obj.sec;
      }
      countDownList.push(obj);
      // console.log(that.data.countDownList)
    });
    that.setData({
      countDownList: countDownList
    })
    if (that.data.ifstart == 3) {
      that.clear()
    } else {
      var timer = setTimeout(that.countDown, 1000);
      setTimeout(function() {
        that.setData({
          timer: timer
        })
      })
    }
    // console.log(that.data.countDownList)
  },
  // 关闭定时器
  clear() {
    let that = this
    clearTimeout(that.data.timer)
    this.setData({
      timer: ''
    })
  },
  // 继续代销
  goonsell() {
    let that = this
    wx.showModal({
      title: '是否继续代销',
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/goods/page/goodsFabu/goonsell/goonsell?goodsId=' + that.data.goodsid,
          })
        } else {
          console.log('点击取消回调')
        }
      }
    })
  },
  // 获取商品信息
  getgoodsinfo() {
    let that = this
    wx.request({
      url: app.globalData.myurl,
      data: {
        cmd: "consignmentGoodsDetails",
        shopId: wx.getStorageSync('shopId'),
        goodsId: that.data.goodsid
      },
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      },
      success(res) {
        if (res.data.zjstate == 1) {
          setTimeout(function () {
            wx.hideLoading()
            wx.stopPullDownRefresh() //停止下拉刷新
          }, 0)
          setTimeout(function () {
            wx.showModal({
              title: '您的账号已在其他设备登录，请重新登录！',
              showCancel: false, //是否显示取消按钮false去掉取消按钮
              success: function (res) {
                if (res.confirm) {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                } else {
                  wx.clearStorageSync()
                  wx.reLaunch({
                    url: '/pages/login/login',
                  })
                }
              }
            })
          }, 0)
          return
        }
        console.log(res)
        if (res.data.result == 1) {
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
          setTimeout(function() {
            wx.showToast({
              title: res.data.resultNote,
              icon: 'none',
              duration: 1500
            })
          }, 0)
        } else {
          let quyulist = []
          for (let i in res.data.salesArea) {
            // console.log(i)
            quyulist.push(res.data.salesArea[i])
          }
          let daixiaojsm = (new Date(res.data.act.endTtime.replace(/-/g, '/'))).getMonth() + 1
          let daixiaojsd = (new Date(res.data.act.endTtime.replace(/-/g, '/'))).getDate()
          let daixiaojs = daixiaojsm + '月' + daixiaojsd + '日' + (res.data.act.endTtime).substring(10)

          let lingshoujsm = (new Date(res.data.act.saleeTime.replace(/-/g, '/'))).getMonth() + 1
          let lingshoujsy = (new Date(res.data.act.saleeTime.replace(/-/g, '/'))).getDate()
          let lingshoujs = lingshoujsm + '月' + lingshoujsy + '日' + (res.data.act.saleeTime).substring(10)

          let jiesuanjsm = (new Date(res.data.act.accteTime.replace(/-/g, '/'))).getMonth() + 1
          let jiesuanjsy = (new Date(res.data.act.accteTime.replace(/-/g, '/'))).getDate()
          let jiesuanjs = jiesuanjsm + '月' + jiesuanjsy + '日' + (res.data.act.accteTime).substring(10)
          // 倒计时
          let ifstart
          var endTimeList = []
          if (res.data.act.limitState == 1) {
            var newTime = new Date().getTime()
            var startTime = new Date(res.data.act.limitStartTime).getTime();
            var endTime = new Date(res.data.act.limitEndTime).getTime();
            // console.log(startTime, newTime, startTime - newTime)
            if (startTime > newTime) {
              ifstart = 2
              var str = res.data.act.limitStartTime.replace(/-/g, "/")
              endTimeList.push(str)
              that.setData({
                goodsinfo: res.data,
                leiIndex: res.data.state,
                daixiaojs: daixiaojs,
                lingshoujs: lingshoujs,
                jiesuanjs: jiesuanjs,
                ifstart: ifstart,
                actEndTimeList: endTimeList,
                quyulist: quyulist
              })
              that.countDown()
            } else if (newTime < endTime) {
              ifstart = 1
              var str = res.data.act.limitEndTime.replace(/-/g, "/")
              endTimeList.push(str)
              that.setData({
                goodsinfo: res.data,
                leiIndex: res.data.state,
                daixiaojs: daixiaojs,
                lingshoujs: lingshoujs,
                jiesuanjs: jiesuanjs,
                ifstart: ifstart,
                actEndTimeList: endTimeList,
                quyulist: quyulist
              })
              that.countDown()
            } else {
              ifstart = 3
              that.setData({
                goodsinfo: res.data,
                leiIndex: res.data.state,
                daixiaojs: daixiaojs,
                lingshoujs: lingshoujs,
                jiesuanjs: jiesuanjs,
                ifstart: ifstart,
                quyulist: quyulist
              })
            }
          } else {
            ifstart = 3
            that.setData({
              goodsinfo: res.data,
              leiIndex: res.data.state,
              daixiaojs: daixiaojs,
              lingshoujs: lingshoujs,
              jiesuanjs: jiesuanjs,
              ifstart: ifstart,
              quyulist: quyulist
            })
          }
          setTimeout(function() {
            wx.hideLoading()
          }, 0)
        }
      }
    });
  },
  // 删除商品
  toshanchu() {
    let that = this
    wx.showModal({
      title: '是否确定删除商品',
      success: function(res) {
        if (res.confirm) {
          setTimeout(function() {
            wx.showLoading({
              title: '加载中',
            })
          }, 0)
          wx.request({
            url: app.globalData.myurl,
            data: {
              cmd: "delGood",
              userId: wx.getStorageSync('userId'),
              goodsId: that.data.goodsid
            },
            header: {
              "content-type": "application/x-www-form-urlencoded",
              "token": wx.getStorageSync('token')
            },
            success(res) {
              if (res.data.zjstate == 1) {
                setTimeout(function () {
                  wx.hideLoading()
                  wx.stopPullDownRefresh() //停止下拉刷新
                }, 0)
                setTimeout(function () {
                  wx.showModal({
                    title: '您的账号已在其他设备登录，请重新登录！',
                    showCancel: false, //是否显示取消按钮false去掉取消按钮
                    success: function (res) {
                      if (res.confirm) {
                        wx.clearStorageSync()
                        wx.reLaunch({
                          url: '/pages/login/login',
                        })
                      } else {
                        wx.clearStorageSync()
                        wx.reLaunch({
                          url: '/pages/login/login',
                        })
                      }
                    }
                  })
                }, 0)
                return
              }
              setTimeout(function() {
                wx.hideLoading()
              }, 0)
              setTimeout(function() {
                wx.showToast({
                  title: res.data.resultNote,
                  icon: 'none',
                  duration: 1500
                })
              }, 0)
              if (res.data.result == 1) {} else {
                setTimeout(function() {
                  wx.navigateBack({
                    delta: 1
                  })
                }, 1500)
              }
            }
          });
        } else {
          console.log('点击取消回调')
        }
      }
    })
  },
  // 设置限时活动
  todaixiaoXianshi() {
    wx.navigateTo({
      url: '/pages/goods/page/goodsXiangqing/daixiaoxianshishez/daixiaoxianshishez?goodsId=' + this.data.goodsid,
    })
  },
  // 去代销订单
  todianpuxiangqing() {
    wx.navigateTo({
      url: '/pages/order/page/daixiaoDingdan/goodsdingdanList/goodsdingdanList?regoodsId=' + this.data.goodsid,
    })
  },
  // 修改商品
  toxiuGai() {
    wx.navigateTo({
      url: '/pages/goods/page/goodsFabu/daixiaoFabu/daixiaoFabu?goodsId=' + this.data.goodsid,
    })
  },
  // 重新申请
  tochongxinSQ() {
    let that = this
    wx.showModal({
      title: '是否重新申请',
      success: function(res) {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/goods/page/goodsFabu/daixiaoFabu/daixiaoFabu?goodsId=' + that.data.goodsid,
          })
        } else {
          console.log('点击取消回调')
        }
      }
    })
  },
  // 切换头部
  changeIndex(e) {
    let that = this
    console.log(e.currentTarget.dataset.index)
    that.setData({
      headIndex: e.currentTarget.dataset.index
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    let that = this
    that.setData({
      goodsid: options.goodsid,
      fixindex: options.fixindex,
    })
    if (options.flag == 0) {
      that.setData({
        fixindex: '1',
      })
    } else if (options.flag == 1) {
      that.setData({
        fixindex: '2',
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let that = this
    setTimeout(function() {
      wx.showLoading({
        title: '加载中',
      })
    }, 0)
    that.getgoodsinfo()
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    let that = this
    clearTimeout(that.data.timer)
    this.setData({
      timer: ''
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    let that = this
    clearTimeout(that.data.timer)
    this.setData({
      timer: ''
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})